package com.dy.分类.哈希表和字符串._93_复原IP地址;

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<String> restoreIpAddresses(String s) {
        List<String> res = new ArrayList<>();
        if (s.length() == 0) return res;
        int n = s.length();
        for (int i = 0; i < 3; i++) {
            for (int j = i + 1; j < i + 4; j++) {
                for (int k = j + 1; k < j + 4; k++) {
                    if (i + 1 > n) continue;
                    String s1 = s.substring(0, i + 1);
                    if (i + 1 > n - 1 || j + 1 > n) continue;
                    String s2 = s.substring(i + 1, j + 1);
                    if (j + 1 > n - 1 || k + 1 > n) continue;
                    String s3 = s.substring(j + 1, k + 1);
                    if (k + 1 > n - 1) continue;
                    String s4 = s.substring(k + 1);
                    if (helper(s1) && helper(s2) && helper(s3) && helper(s4))
                        res.add(s1 + "." + s2 + "." + s3 + "." + s4);

                }
            }
        }
        return res;
    }

    private boolean helper(String s1) {
        if (s1.length() > 3 || s1.length() == 0 || (s1.charAt(0) == '0' && s1.length() > 1) || Integer.parseInt(s1) > 255) {
            return false;
        }
        return true;
    }

    public List<String> restoreIpAddresses2(String s) {
        List<String> res = new ArrayList<>();

        helper(0, s, res, "", 0);
        return res;
    }

    public void helper(int start, String s, List<String> res, String tmp, int part) {
        if (start == s.length() && part == 4) {
            res.add(tmp.substring(0,tmp.length()-1));
            return;
        }
        if(part>=4) return;
        for (int i = start; i < start + 3 && i < s.length(); i++) {
            //如果第一个字符是0，那么直接剪枝，无需循环
            if (i == start && s.charAt(i) == '0') {
                helper(i+1,s,res,tmp+"0.",part+1);
                break;
            }
            String k;
            if(Integer.parseInt((k=s.substring(start,i+1)))<=255){
                helper(i+1,s,res,tmp+k+".",part+1);
            }
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.restoreIpAddresses2("25525511135"));

    }
}
